package com.hundsun.cprs.yyt.service.system.service.impl;

import com.hundsun.cprs.yyt.common.base.BaseService;
import com.hundsun.cprs.yyt.common.exception.ServiceCodeException;
import com.hundsun.cprs.yyt.service.system.dto.TradingTimePeriodReponse;
import com.hundsun.cprs.yyt.service.system.enums.EnumBussinessParam;
import com.hundsun.cprs.yyt.service.system.service.BusinessParamHelper;
import com.hundsun.cprs.yyt.service.system.service.BussinessParamService;
import com.hundsun.cprs.yyt.service.system.service.TradingTimePeriodService;
import com.hundsun.cprs.yyt.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class TradingTimePeriodServiceImpl extends BaseService implements TradingTimePeriodService {

    private static final String defaultTimePeriod = "00:00-16:00,19:00-23:59";

    @Autowired
    private BussinessParamService bussinessParamService;

    @Override
    public TradingTimePeriodReponse isTradingTimePeriod() {
        TradingTimePeriodReponse response = new TradingTimePeriodReponse();
        //交易时间段控制
        String tradingTimePeriod = BusinessParamHelper.getStringValue(bussinessParamService,EnumBussinessParam.TRADING_TIME_PERIOD_CONTROL,defaultTimePeriod);
        if (tradingTimePeriod != null){
            String[] timePeriodArray = tradingTimePeriod.split(",");
            try{
                //解析时间端一
                String timePeriodOne = timePeriodArray[0];
                String[] timePeriodArrayOne = timePeriodOne.split("-");
                String beforeTimeOne = timePeriodArrayOne[0];
                String afterTimeOne = timePeriodArrayOne[1];
                //解析时间段二
                String timePeriodTwo = timePeriodArray[1];
                String[] timePeriodArrayTwo = timePeriodTwo.split("-");
                String beforeTimeTwo = timePeriodArrayTwo[0];
                String afterTimeTwo = timePeriodArrayTwo[1];
                //当前时间不在两个时间段内，则不允许交易
                if (!DateUtil.checkDateBetween(beforeTimeOne,afterTimeOne,new Date()) && !DateUtil.checkDateBetween(beforeTimeTwo,afterTimeTwo,new Date())){
                    response.setFlag(false);
                    response.setTimePeriod(tradingTimePeriod);
                }
            }catch (Exception e){
                logger.error("系统交易时间段格式有误，默认为24小时交易" + e);
                throw e;
            }
        }
        return response;
    }
}
